package com.tp.controller.system;

import java.util.List;

import com.jfinal.aop.Inject;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.plugin.activerecord.Page;
import com.tp.base.BaseController;
import com.tp.model.sys.SysOrg;
import com.tp.model.sys.SysUser;
import com.tp.service.OrgService;

/**
 * 组织机构
 * 
 * @author TP
 *
 */
@ControllerBind(controllerKey = "/system/org")
public class OrgController extends BaseController {

	private static final String path = "/pages/system/org/org_";

	@Inject
	OrgService service;

	public void index() {
		render(path + "list.html");
	}

	public void list() {
		SysOrg model = getModelByAttr(SysOrg.class);
		// 排序
		String orderBy = getBaseForm().getOrderBy();
		Page<SysOrg> page = service.getPageByWhere(model, orderBy, getPaginator());
		renderCount(page.getTotalRow(), page.getList());
	}

	public void form() {
		int id = getParaToInt("id", 0);
		if (id == 0) {
			SysOrg model = new SysOrg();
			model.setStatus(1);
			setAttr("model", model);
			setAttr("orgSelect", service.selectOrg(0));
		} else {
			SysOrg model = new SysOrg().dao().findById(id);
			setAttr("model", model);
			setAttr("orgSelect", service.selectOrg(model.getId()));
		}
		render(path + "form.html");
	}

	public void save() {
		SysOrg model = getModel(SysOrg.class);
		// 日志添加
		Integer userid = getUID();
		String now = getNow();
		boolean flag = false;
		if (model.getInt("id") != null && model.getInt("id") > 0) { // 更新
			model.set("update_id", userid);
			model.set("update_time", now);
			flag = model.update();
		} else { // 新增
			model.remove("id");
			model.set("create_id", userid);
			model.set("create_time", now);
			flag = model.save();
		}
		if (flag) {
			renderOk("保存成功");
		} else {
			renderFail("保存失败");
		}
	}

	public void delete() {
		boolean flag = true;
		SysOrg model = new SysOrg();
		// 删除前先验证是否存在子节点 以及 是否存在关联用户
		List<SysOrg> orgList = model.dao().findByWhere("where parent_id=?", getParaToInt("id", -1));
		if (orgList != null && orgList.size() > 0) {
			flag = false;
		}
		List<SysUser> userList = new SysUser().dao().findByWhere("where org_id=?", getParaToInt("id", -1));
		if (flag && userList != null && userList.size() > 0) {
			flag = false;
		}
		if (flag) {
			// 日志添加
			Integer userid = getUID();
			String now = getNow();
			model.put("update_id", userid);
			model.put("update_time", now);
			flag = model.deleteById(getParaToInt("id", -1));
			if (flag) {
				renderOk("删除成功");
			} else {
				renderFail("删除失败");
			}
		} else {
			renderFail("删除失败，有子节点或节点下有关联用户");
		}
	}

}
